package pl.msikora.android.lapmagic.view;

import pl.msikora.android.lapmagic.R;
import pl.msikora.android.lapmagic.database.LapMagicDatabaseHelper;
import pl.msikora.android.lapmagic.database.PointsTable;
import pl.msikora.android.lapmagic.database.TracksTable;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

/**
 * View which enables set up for a new session.
 * 
 * @author Maciej Sikora
 * 
 */
public class PrepareSessionActivity extends SherlockActivity {

	private final String TAG = "PrepareSessionActivity";
	
	private Spinner tracksSpinner = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.prepare_session);
		tracksSpinner = (Spinner) findViewById(R.id.selectTrack);
		ActionBar actionBar = getSupportActionBar();
		actionBar.setHomeButtonEnabled(true);
		actionBar.setTitle(R.string.prepare_session_title);
	}

	@Override
	public void onStart() {
		super.onStart();
		Log.d(TAG, "Filling the spinner with data during start");
		fillData();
	}
	
	@Override
	public void onDestroy() {
		Log.d(TAG, "Closing database on destroy");
		LapMagicDatabaseHelper.getInstance(this).close();
		super.onDestroy();
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case android.R.id.home:
    		Intent home = new Intent(this, MainActivity.class);
    		home.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    		startActivity(home);
    		return true;
    	}
    	return super.onOptionsItemSelected(item);
    }
    
    public void newTrack(View view) {
		Intent intent = new Intent(this, TrackDetailActivity.class);
		startActivity(intent);
    }
    
    public void startSession(View view) {
    	if (tracksSpinner.getSelectedItemPosition() ==
    			AdapterView.INVALID_POSITION) {
    		Toast.makeText(this, R.string.prepare_session_please_select_track,
    				Toast.LENGTH_SHORT).show();
    	}

    	else if (trackHasStart(tracksSpinner.getSelectedItemId())) {

    		// selected track is fine - start
	    	Cursor cursor = (Cursor) tracksSpinner.getSelectedItem();
	    	Toast.makeText(this, getString(R.string.prepare_session_start)
	    			+ " " + cursor.getString(cursor.getColumnIndexOrThrow(
	    			TracksTable.COLUMN_NAME)), Toast.LENGTH_LONG).show();
	    	Intent intent = new Intent(this, RunSessionActvity.class);
	    	intent.putExtra("id", tracksSpinner.getSelectedItemId());
	    	startActivity(intent);
    	}

    	else {
    		Toast.makeText(this, R.string.prepare_session_bad_track_message,
    				Toast.LENGTH_LONG).show();
    	}
    }
    
    private void fillData() {
		SQLiteDatabase db = LapMagicDatabaseHelper.getInstance(this)
				.getReadableDatabase();
		Cursor tracksCursor = db.query(TracksTable.TABLE_TRACKS, new String[] {
				TracksTable.COLUMN_ID, TracksTable.COLUMN_NAME }, null,
				null, null, null, null);
		startManagingCursor(tracksCursor);
		
		String[] from = new String[] { TracksTable.COLUMN_NAME };
		int[] to = new int[] { android.R.id.text1 };
		SimpleCursorAdapter tracks = 
				new SimpleCursorAdapter(this,
						android.R.layout.simple_spinner_item, tracksCursor, 
						from, to, 0);
        tracks.setDropDownViewResource(
        		android.R.layout.simple_spinner_dropdown_item);
		tracksSpinner.setAdapter(tracks);
	}

    private boolean trackHasStart(long trackId) {
    	SQLiteDatabase db = LapMagicDatabaseHelper.getInstance(this)
    			.getReadableDatabase();
		Cursor pointsCursor = db.query(PointsTable.TABLE_POINTS, new String[] {
				PointsTable.COLUMN_TYPE }, PointsTable.COLUMN_TRACK_ID + " = "
				+ trackId + " and " + PointsTable.COLUMN_TYPE + " = '"
				+ getString(R.string.track_detail_point_type_start) + "'",
				null, null, null, null);

		int count = pointsCursor.getCount();
		pointsCursor.close();

		if (count == 1) // only one start defined - OK
			return true;

		else { //expected count == 0
			if (count > 1) // this shouldn't happen
				Log.e(TAG, "track id = " + trackId + " has multiple start points"
					+ " - this shouldn't happen");
			return false;
		}
    }
	
}
